package com.ifcar.app.weibo;

import java.util.Map;

import net.oauth.OAuth;
import t4j.TBlog;
import t4j.TBlogException;
import t4j.data.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.AccountSettingActivity;
import com.ifcar.app.activity.BaseActivity;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.Util;

public class WeiboLogin extends BaseActivity {
	
	private WebView webView;
	private TextView title;
	private static String tokenKey = "";
	private static String tokenSecrect = "";
	private int weibo_type = -1;
	private LinearLayout loadingbar;
	private ImageView top_image;
	private t4j.http.RequestToken neteaserequestToken = null;
	
	public static final int PARAM_WEIBO_TYPE = -1;
    public static final int PARAM_WEIBO_TYPE_SINA = PARAM_WEIBO_TYPE + 1;
    public static final int PARAM_WEIBO_TYPE_QQ = PARAM_WEIBO_TYPE_SINA + 1;
    public static final int PARAM_WEIBO_TYPE_NETEASE = PARAM_WEIBO_TYPE_QQ + 1;
    public static final int PARAM_WEIBO_TYPE_RENREN = PARAM_WEIBO_TYPE_NETEASE + 1;
    public static final int PARAM_WEIBO_TYPE_YDNOTE = PARAM_WEIBO_TYPE_RENREN + 1;
    public static final int PARAM_WEIBO_TYPE_SMS = PARAM_WEIBO_TYPE_YDNOTE + 1;
    public static final int PARAM_WEIBO_TYPE_EMAIL = PARAM_WEIBO_TYPE_SMS + 1;
	
	public static final String sinaCustomKey = "3857427664";
	public static final String sinaCustomSecrect = "1901a3e5e35c98953ef4df53095ae02f";
	
	public static final String neteaseCustomKey = "zK8tVL3Nj4JOgqFL";
	public static final String neteaseCustomSecrect = "l6Kkp4nszxRx3OBndw7C8ZRjthvzTqEv";
	
	public static final String qqCustomKey = "2ffe39c660f146df91ffb206a9d44bd5";
	public static final String qqCustomSecrect = "63261cea4dc8b5c74ed5eefc0f149acd";
	
	public static String RENREN_API_KEY = "b7f53f3f6873425d88d8047b2d42d041";
    public static String RENREN_SECRET_KEY = "6ae2193b45fe41cd9c13ed2a36cc1e9a";
    public static String RENREN_APP_ID = "155516";
    
	public static final String callbackUrl = "weibo4andriod://AccountSettingActivity";
	public static final String callbackUrlPrefix = "weibo4andriod";
	
	private Renren mRenren;
	private ProgressDialog progressDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weibologin);
				
		Bundle bundle = this.getIntent().getExtras();
		if(bundle != null) {
			weibo_type  = bundle.getInt("weibo_type");
		}
		
		loadingbar = (LinearLayout) findViewById(R.id.weibologin_loadingbar);
		loadingbar.setVisibility(View.VISIBLE);
		title = (TextView) findViewById(R.id.top_main_text);
		
		webView = (WebView) findViewById(R.id.weibo_webview);
		CookieSyncManager.createInstance(getApplicationContext());
        CookieManager.getInstance().removeAllCookie();
		webView.getSettings().setJavaScriptEnabled(true);	 
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setDatabaseEnabled(false);
        webView.getSettings().setSaveFormData(false);
        webView.getSettings().setSavePassword(false);
        webView.clearCache(true);
		String host = Tools.getHostbyWAP(this);
		if(null!=host){
		    webView.setHttpAuthUsernamePassword(host, "80", "", "");
		}
		webView.addJavascriptInterface(new WebHandler(), "webhandler");
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				loadingbar.setVisibility(View.GONE);
				view.loadUrl("javascript:(function() {" +
                        "document.getElementsByClassName('thridBgbor')[0].style.border='0px';"+
                "document.getElementsByClassName('thridBgbor')[0].children[0].style.border='0px';" +
                "document.getElementsByClassName('linedot_ph')[0].style.paddingTop = '0px';" +
                "document.getElementsByClassName('opthTable')[0].style.paddingTop = '0px';" +
                "document.getElementsByClassName('opthTable')[0].style.paddingBottom = '0px';" +
                "document.getElementsByClassName('thridBgbor')[0].style.border='0px';" +
                "document.getElementsByClassName('thridBgbor')[0].children[0].style.border='0px';" +
                "document.getElementsByClassName('title')[0].innerHTML = document.getElementsByClassName('title')[0].innerHTML.replace('<br><br>','');" +
                "document.getElementsByClassName('btn_gray')[0].href='close://';})()");
				
				if((YdNoteLoginHelper.getBaseUrl() + YdNoteLoginHelper.OAUTH_PREFIX + YdNoteLoginHelper.AUTHORIZEURL).equals(url)){
					loadingbar.setVisibility(View.VISIBLE);
	            	view.loadUrl("javascript:window.webhandler.show(document.body.innerHTML);");
				}
			}

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				// TODO Auto-generated method stub
				try {
					if(handler != null)
					handler.proceed();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			@Override
	        public void onReceivedError(WebView view, int errorCode, String description,
	                String failingUrl) {
	            super.onReceivedError(view, errorCode, description, failingUrl);
	            loadingbar.setVisibility(View.GONE);
	        }
		

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
			    
                String host = Tools.getHostbyWAP(WeiboLogin.this);
                if(null!=host){

                    if (!url.startsWith(callbackUrl) && !url.endsWith(callbackUrl)) {
                        int index = url.indexOf(callbackUrl);
                        if (index != -1) {
                            url = url.substring(index);
                        }
                    }
                
                }
                
			    
			    if(ActionProcess(view, url)) {
	                WeiboLogin.this.finish();
	                return true;
	            } 
			    
			   //有道的授权界面需要加入mobile参数
			    if(weibo_type == PARAM_WEIBO_TYPE_YDNOTE){
			        url = url + "&display=mobile";
			    }
			    
				view.loadUrl(url);
				
		        return true;
			}
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				
				super.onPageStarted(view, url, favicon);
				if(weibo_type == PARAM_WEIBO_TYPE_RENREN && ActionProcess(view, url)) {
					WeiboLogin.this.finish();
				} 
				loadingbar.setVisibility(View.VISIBLE);
			}
			
		});
		
		if(weibo_type == PARAM_WEIBO_TYPE_SINA) {
			title.setText(" 绑定新浪微博 ");
			new Thread() {
				public void run() {
					sinaWeiboLogin();
				}
			}.start();
			
			
		}
		else if(weibo_type == PARAM_WEIBO_TYPE_QQ) {
			title.setText(" 绑定腾讯微博");
			new Thread() {
				public void run() {
					qqWeiboLogin();
				}
			}.start();
			
		}
		else if(weibo_type == PARAM_WEIBO_TYPE_NETEASE) {
			title.setText(" 绑定网易微博");
			new Thread() {
				public void run() {
					neteaseWeiboLogin();
				}
			}.start();
			
		}else if(weibo_type == PARAM_WEIBO_TYPE_RENREN){
		    title.setText(" 绑定人人网");
		    new Thread(){
		        public void run(){
		            renrenLogin();
		        }
		    }.start();
		} else if(weibo_type == PARAM_WEIBO_TYPE_YDNOTE){
			title.setText(" 绑定有道云笔记");
		    new Thread(){
		        public void run(){
		            ydnoteLogin();
		        }
		    }.start();
		}
		
		progressDialog = new ProgressDialog(app);
        progressDialog.setMessage("正在处理分享帐号绑定");
	}
	
	class WebHandler {
		public void show(String data) {
			String FLAG = "<!-- verifier -->";
			
			int start = data.indexOf(FLAG) + FLAG.length();
			int end = data.lastIndexOf(FLAG);
			
			String verifier = data.substring(start, end).trim();
			try {
	        	
	        	YdNoteLoginHelper h = new YdNoteLoginHelper();
	        	Map<String, String> map = h.requestVerifier(reqeustToken, reqeustsceset, verifier);

	        	String auth_token = map.get("oauth_token");
	        	String auth_verifier = map.get("oauth_token_secret");
	        	
	        	if(!TextUtils.isEmpty(auth_token) && !TextUtils.isEmpty(auth_verifier)){
		        	db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where "
		                    + NewsSQLiteOpenHelper.OAUTH_TYPE + "='ydnote'");
		            ContentValues initialValues = new ContentValues();
		            initialValues.put(NewsSQLiteOpenHelper.OAUTH_TYPE, "ydnote");
		            initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN, auth_token);
		            initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET, auth_verifier);
		            initialValues.put(NewsSQLiteOpenHelper.OAUTH_NAME, "");
		            db.insert(NewsSQLiteOpenHelper.OAUTH_TABLE, null, initialValues);
		            
		            handler.sendEmptyMessage(1);
		            
		            Intent intent = new Intent(WeiboLogin.this,AccountSettingActivity.class);
		            setResult(Activity.RESULT_OK, intent);
		            finish();
		            
		        }else{
		            handler.sendEmptyMessage(2);
		        }
        	} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
		}
	}
	
	private boolean ActionProcess(WebView view, String url) {  
		
		switch(checkUrl(url)) {
			case ACTION_FAILED: {
	           
				Intent intent = new Intent(WeiboLogin.this,AccountSettingActivity.class);
	            WeiboLogin.this.setResult(Activity.RESULT_CANCELED, intent);
	            view.stopLoading();
	            loadingbar.setVisibility(View.GONE);
	            return true;
	        }
	        case ACTION_PROCCESSED: {
	           
	            storeAccessInfo(Uri.parse(url));
	            Intent intent = new Intent(WeiboLogin.this,AccountSettingActivity.class);
	            WeiboLogin.this.setResult(Activity.RESULT_OK, intent);
	            
	            view.stopLoading();
	            loadingbar.setVisibility(View.GONE);
	            return true;
	        }
	        case ACTION_UNPROCCESS:
	        	break;
		}
	    return false;
	}
	
	/**
     * 存储AccessToken信息
     * @param uri
     */
    private void storeAccessInfo(final Uri uri) {
        switch(weibo_type) {
        case PARAM_WEIBO_TYPE_SINA:
        	
        	
        	try {
        		RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
        		weibo4android.http.AccessToken accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
        		
        		if(accessToken == null || accessToken.getToken() == null || accessToken.getToken().equals(""))
        			handler.sendEmptyMessage(2);
        		else {
        			
        			db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where "
        					+ NewsSQLiteOpenHelper.OAUTH_TYPE + "='sina'");
        			
        			ContentValues initialValues = new ContentValues();
        			initialValues.put(NewsSQLiteOpenHelper.OAUTH_TYPE, "sina");
        			initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN, accessToken.getToken());
        			initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret());
        			db.insert(NewsSQLiteOpenHelper.OAUTH_TABLE, null, initialValues);
        			
        			handler.sendEmptyMessage(1);
        		}
                        
        	} catch (Exception e) {
        		e.printStackTrace();
        		handler.sendEmptyMessage(2);
        	}
        	
        	
        	
            break;
        case PARAM_WEIBO_TYPE_QQ:
        	
        	
        	QWeiboSyncApi api = new QWeiboSyncApi();
        	String response = null;
        	String customKey = WeiboLogin.qqCustomKey;
        	String customSecrect = WeiboLogin.qqCustomSecrect;
        	response = api.getAccessToken(customKey, customSecrect, WeiboLogin.getQQToken(), WeiboLogin.getQQTokenSecret(), uri.getQueryParameter("oauth_verifier"));
        	
        	
        	String tokenKey = "";
        	String tokenSecrect = "";
        	String name = "";
        	boolean status = true;
        	if (response == null || response.equals("")) {
        		status = false;
        	} else {
        		String[] tokenArray = response.split("&");
        		
        		if (tokenArray.length < 2) {
        			status = false;
        		} else {
        			String strTokenKey = tokenArray[0];
        			String strTokenSecrect = tokenArray[1];
        			String strName = "";
        			if(tokenArray.length > 2) {
        				strName = tokenArray[2];
        				String[] names = strName.split("=");
        				if(names.length >= 2)
        					name = names[1];
        			}
        			
        			
        			String[] token1 = strTokenKey.split("=");
        			if (token1.length < 2) {
        				status = false;
        			} else {
        				tokenKey = token1[1];
        				
        				String[] token2 = strTokenSecrect.split("=");
        				if (token2.length < 2) {
        					status = false;
        				} else {
        					tokenSecrect = token2[1];
        				}
        				
        			}
        			
        		}
        	}
                    
        	if(!status) {
        		status = true;
        		handler.sendEmptyMessage(2);
        	} else {
        		
        		db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where "
        				+ NewsSQLiteOpenHelper.OAUTH_TYPE + "='qq'");
        		
        		ContentValues initialValues = new ContentValues();
        		initialValues.put(NewsSQLiteOpenHelper.OAUTH_TYPE, "qq");
        		initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN, tokenKey);
        		initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET, tokenSecrect);
        		initialValues.put(NewsSQLiteOpenHelper.OAUTH_NAME, name);
        		db.insert(NewsSQLiteOpenHelper.OAUTH_TABLE, null, initialValues);
        		
        		
        		handler.sendEmptyMessage(1);
        	}
        	
        	break;
        case PARAM_WEIBO_TYPE_NETEASE:
        	
        	
        	try {
                TBlog tblog = new TBlog();  
                t4j.http.AccessToken accessToken = tblog.getOAuthAccessToken(neteaserequestToken);
                tokenKey = accessToken.getToken();
                tokenSecrect = accessToken.getTokenSecret();
                 if(null!=tokenKey || !"".equals(tokenKey) || null!=tokenSecrect || !"".equals(tokenSecrect)){
                        
                    tblog.setToken(tokenKey, tokenSecrect);
                    User user = tblog.verifyCredentials();
                    name = user.getName();
                    db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where "
                            + NewsSQLiteOpenHelper.OAUTH_TYPE + "='netease'");
                    ContentValues initialValues = new ContentValues();
                    initialValues.put(NewsSQLiteOpenHelper.OAUTH_TYPE, "netease");
                    initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN, tokenKey);
                    initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET, tokenSecrect);
                    initialValues.put(NewsSQLiteOpenHelper.OAUTH_NAME, name);
                    db.insert(NewsSQLiteOpenHelper.OAUTH_TABLE, null, initialValues);
                    
                    handler.sendEmptyMessage(1);
                    
                }else{
                    handler.sendEmptyMessage(2);
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                handler.sendEmptyMessage(2);
            } catch (TBlogException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                handler.sendEmptyMessage(2);
            }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                handler.sendEmptyMessage(2);
            }
        
            break;
        case PARAM_WEIBO_TYPE_RENREN:
            String accessToken = null;
            
            Bundle values = Util.parseUrl(uri.toString());
            CookieSyncManager.getInstance().sync();
            accessToken = values.getString("access_token"); 
            
            if (accessToken != null) {
                
                try {
                    mRenren = new Renren(WeiboLogin.RENREN_API_KEY, WeiboLogin.RENREN_SECRET_KEY, WeiboLogin.RENREN_APP_ID, WeiboLogin.this);
                    mRenren.updateAccessToken(accessToken);
                    tokenKey = mRenren.getAccessToken();
                    tokenSecrect = mRenren.getAccessToken();
                     if(null!=tokenKey || !"".equals(tokenKey) || null!=tokenSecrect || !"".equals(tokenSecrect)){
                           
                         
                       
                        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where "
                                + NewsSQLiteOpenHelper.OAUTH_TYPE + "='renren'");
                        ContentValues initialValues = new ContentValues();
                        initialValues.put(NewsSQLiteOpenHelper.OAUTH_TYPE, "renren");
                        initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN, tokenKey);
                        initialValues.put(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET, tokenSecrect);
                        initialValues.put(NewsSQLiteOpenHelper.OAUTH_NAME, "");
                        db.insert(NewsSQLiteOpenHelper.OAUTH_TABLE, null, initialValues);
                        
                        handler.sendEmptyMessage(1);
                        
                    }else{
                        handler.sendEmptyMessage(2);
                    }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    mRenren.logout(WeiboLogin.this);
                    handler.sendEmptyMessage(2);
                }
            } else {
                mRenren.logout(WeiboLogin.this);
                handler.sendEmptyMessage(2);
            }
            break;
        }
    }
	
	private static final int ACTION_PROCCESSED = 0;  //处理完成
    private static final int ACTION_UNPROCCESS = 1;  //未处理完成
    private static final int ACTION_FAILED = 2;      //出现错误
    
    private int checkUrl(String url) {
        if (url.startsWith("http://graph.renren.com/login_deny/")) {
            return ACTION_FAILED;
        } else if(url.startsWith("close:")) {
            return ACTION_PROCCESSED;
        } else if (url.startsWith(Renren.DEFAULT_REDIRECT_URI)) {
            Bundle values = Util.parseUrl(url);
            String error = values.getString("error");//OAuth返回的错误代码
            if (error != null) {
                return ACTION_FAILED;
            } else {
                return ACTION_PROCCESSED;
            }
            
        } else if(url.startsWith(callbackUrlPrefix)) {
            return ACTION_PROCCESSED;
        } else if(url.startsWith(YdNoteLoginHelper.getBaseUrl() + YdNoteLoginHelper.OAUTH_PREFIX + callbackUrlPrefix) &&  // 有道开头，并且回调开头
        		url.substring((YdNoteLoginHelper.getBaseUrl() + YdNoteLoginHelper.OAUTH_PREFIX).length()).startsWith(callbackUrlPrefix)){
        	return ACTION_PROCCESSED;
        }
        return ACTION_UNPROCCESS;
    }
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			switch(msg.what) {
			case 0:
				Toast.makeText(app, "加载页面失败,请重试", Toast.LENGTH_SHORT).show();
				break;
			
            case 1:
                progressDialog.dismiss();
                Toast.makeText(app, "绑定成功", Toast.LENGTH_SHORT).show();
                
                break;
            case 2: 
                progressDialog.dismiss();
                Toast.makeText(app, "绑定失败，请重试", Toast.LENGTH_SHORT).show();
                
                break;
			}
		}
		
	};
	
	private void sinaWeiboLogin() {
		Weibo.CONSUMER_KEY = sinaCustomKey;
		Weibo.CONSUMER_SECRET = sinaCustomSecrect;
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	Weibo weibo = new Weibo();
    	
    	String host = Tools.getHostbyWAP(WeiboLogin.this);
    	if(null!=host){
    	    weibo.setHttpProxy(host, 80);
    	}
    	
    	RequestToken requestToken;
		try {
			requestToken = weibo.getOAuthRequestToken(callbackUrl);			
			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+"&oauth_callback="+callbackUrl+"&display=wap2.0");
			OAuthConstant.getInstance().setRequestToken(requestToken);
			webView.loadUrl(uri.toString());
		} catch (WeiboException e) {
			e.printStackTrace();
			handler.sendEmptyMessage(0);
		}catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
	}
	
	private void qqWeiboLogin() {
		QWeiboSyncApi api = new QWeiboSyncApi();
		String response = null;
		
		try{
		
		    String host = Tools.getHostbyWAP(WeiboLogin.this);
	        if(null!=host){
	            Tools.setHttpProxy(host, String.valueOf(80));
	        }
		    response = api.getRequestToken(qqCustomKey, qqCustomSecrect, callbackUrl);
	        if (!parseToken(response)) {
	            handler.sendEmptyMessage(0);
	        } else {
	            Uri uri = Uri.parse("http://open.t.qq.com/cgi-bin/authorize?oauth_token=" + tokenKey);
	            webView.loadUrl(uri.toString());
	        } 
		}catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
		
	}
	
	private void neteaseWeiboLogin(){
		
		try {
			System.setProperty("tblog4j.oauth.consumerKey", neteaseCustomKey);
			System.setProperty("tblog4j.oauth.consumerSecret", neteaseCustomSecrect);
			System.setProperty("tblog4j.debug", "false");
			TBlog tblog = new TBlog();
			
			String host = Tools.getHostbyWAP(WeiboLogin.this);
			if(null!=host){
			    tblog.setHttpProxy(host, 80);
			}

			neteaserequestToken = tblog.getOAuthRequestToken();
			Uri uri = Uri.parse(neteaserequestToken.getAuthenticationURL()+"&oauth_callback="+callbackUrl+"&client_type=mobile");//"&from=xweibo");
			webView.loadUrl(uri.toString());
		} catch (TBlogException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
                TBlog tblog = new TBlog();
                
                String host = Tools.getHostbyWAP(WeiboLogin.this);
                if(null!=host){
                    tblog.setHttpProxy(host, 80);
                }

                neteaserequestToken = tblog.getOAuthRequestToken();
                Uri uri = Uri.parse(neteaserequestToken.getAuthenticationURL()+"&oauth_callback="+callbackUrl+"&client_type=mobile");//"&from=xweibo");
                webView.loadUrl(uri.toString());
            } catch (TBlogException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                handler.sendEmptyMessage(0);
            }
			
		}catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
	}
	
	private void renrenLogin() {
        try {   
            
            String host = Tools.getHostbyWAP(WeiboLogin.this);
            if(null!=host){
                Tools.setHttpProxy(host, String.valueOf(80));
            }
            
            Uri uri = Uri.parse(getRenrenAuthorizeUrl(WeiboLogin.this, null, Renren.DEFAULT_REDIRECT_URI, "token", RENREN_API_KEY));
            webView.loadUrl(uri.toString());
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
    }
	
	private void ydnoteLogin() {
        try {   
            
            String host = Tools.getHostbyWAP(WeiboLogin.this);
            if(null!=host){
                Tools.setHttpProxy(host, String.valueOf(80));
            }
            String authorizedURL = getYdnoteAuthorizeUrl();
            if(null != authorizedURL && authorizedURL.length() > 0){
            	webView.loadUrl(authorizedURL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(0);
        }
    }

	private String reqeustToken = null;
	private String reqeustsceset = null;
	/**
	 * 获得有道笔记Auth URL
	 * @return
	 */
    public String getYdnoteAuthorizeUrl() {
    	
    	YdNoteLoginHelper ydHelper = new YdNoteLoginHelper();
    	
    	String authorizedUrl = null;
    	try {
    		// Reqeust_token
    		reqeustToken = null;
    		reqeustsceset = null;
        	Map<String, String> map = ydHelper.requestToken();
        	reqeustToken  = map.get(OAuth.OAUTH_TOKEN);
    		reqeustsceset = map.get(OAuth.OAUTH_TOKEN_SECRET);

    		// Authorize token
	    	authorizedUrl = ydHelper.authorizeToken(map);
	    	authorizedUrl += "&display=mobile";
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	
    	return authorizedUrl;
    }
    
	/**
     * 获得人人网的Auth url
     * @param activity
     * @param permissions
     * @param redirectUrl
     * @param responseType
     * @param apiKey
     * @return
     */
    public String getRenrenAuthorizeUrl(Activity activity, String[] permissions,
            String redirectUrl, String responseType, String apiKey) {
        // 调用CookieManager.getInstance之前
        // 必须先调用CookieSyncManager.createInstance
        CookieSyncManager.createInstance(activity);

        Bundle params = new Bundle();
        params.putString("client_id", apiKey);
        params.putString("redirect_uri", redirectUrl);
        params.putString("response_type", responseType);
        params.putString("display", "touch");
        
        //若开发者提供的权限列表为空，则使用默认权限列表
        if(permissions == null) {
            permissions = Renren.DEFAULT_PERMISSIONS;
        }
        
        if (permissions != null && permissions.length > 0) {
            String scope = TextUtils.join(" ", permissions);
            params.putString("scope", scope);
        }

        String url = Renren.AUTHORIZE_URL + "?" + Util.encodeUrl(params);
        return url;
    }

	static boolean parseToken(String response) {
		if (response == null || response.equals("")) {
			return false;
		}

		String[] tokenArray = response.split("&");

		if (tokenArray.length < 2) {
			return false;
		}

		String strTokenKey = tokenArray[0];
		String strTokenSecrect = tokenArray[1];

		String[] token1 = strTokenKey.split("=");
		if (token1.length < 2) {
			return false;
		}
		tokenKey = token1[1];

		String[] token2 = strTokenSecrect.split("=");
		if (token2.length < 2) {
			return false;
		}
		tokenSecrect = token2[1];
		
		return true;
	}
	
	public static String getQQToken() {
		return tokenKey;
	}
	
	public static String getQQTokenSecret() {
		return tokenSecrect;
	}
	
	public void goBackClick(View view){
		finish();
	}
	
	@Override
	public void onApplyTheme() {
		super.onApplyTheme();
		ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
		themeSettingsHelper.setViewBackgroud(this, R.id.top_main_bottom, R.drawable.top_background);
		themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
		themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
		themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
	}
	
}
